package com.nxcy.student.controller;

import com.nxcy.common.util.MD5Util;
import com.nxcy.mysql.DBUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet(urlPatterns = {"/login.do"})
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        HttpSession session = request.getSession();
        String msg = "";
        if (!(username == null || username.length() == 0 || password == null || password.length() == 0)) {
            DBUtils db = new DBUtils();
            PreparedStatement pstmt = null;
            try {
                pstmt=db.getPreparedStatement("SELECT * from t_user t WHERE (t.username=? or t.phone=? or t.sno=?) AND t.`password`=?");
                pstmt.setString(1, username);
                pstmt.setString(2, username);
                pstmt.setString(3, username);
                pstmt.setString(4, MD5Util.md5(password));
                ResultSet rs = pstmt.executeQuery();
                if (rs.next()) {
                    session.setAttribute("name", rs.getString("name"));
                    db.close();
                    response.sendRedirect("/student/list.do");
                } else {
                   request.setAttribute("msg","用户名密码错误");
                    db.close();
                   request.getRequestDispatcher("/java/05/login.jsp").forward(request,response);
                }
            } catch (Exception e) {
                request.setAttribute("msg",e.getLocalizedMessage());
                db.close();
                request.getRequestDispatcher("/java/05/login.jsp").forward(request,response);
            } finally {
                db.close();
            }
        }


    }
}
